# -*- coding: utf-8 -*-
from django.db import models
from django.utils import simplejson


class Identity(models.Model):
    reg_date = models.DateTimeField(auto_now_add=True)
    identity = models.TextField(primary_key=True)
    jsoned_data = models.TextField()

    def set_data(self, data):
        self.jsoned_data = simplejson.dumps(data)

    def get_data(self):
        return simplejson.loads(self.jsoned_data)

    def get_name(self):
        maybename = self.get_data().get('name')
        if isinstance(maybename, basestring):
            return maybename

        if isinstance(maybename, dict):
            maybename = maybename.get('full_name')
            if isinstance(maybename, basestring):
                return maybename

        return self.identity

    def __unicode__(self):
        return self.identity

    class Meta:
        ordering = ('reg_date',)


class LoginzaUser(models.Model):
    reg_date = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=255, blank=True)
    identities = models.ManyToManyField(Identity)
    is_active = models.BooleanField(default=True)
    login = models.EmailField(null=True)
    password_hash = models.CharField(null=True, max_length=255)

    def clean(self):
        self.name = self.name.strip()

    def __unicode__(self):
        if self.name:
            return self.name
        else:
            return self.identities.all()[0].identity

    class Meta:
        ordering = ('reg_date',)
